import java.nio.ByteBuffer;

public class MyMessage {

	public static short DATA = 1;
	public static short REPLY = 2;
	public static short INIT = 3;
	
	short ID=DATA;
	
	byte[] surnom;
	
	short seq;
	
	short taille;
	
	String message;
	
	ByteBuffer bb;
	
	public MyMessage(){
		ID = DATA; 
	}
	
	public MyMessage(String surnom_var, short seq_var, String content){
		surnom = new byte[6];
		surnom = surnom_var.getBytes();
		seq = seq_var;
		message = content;		
		taille = (short)(2 + 6 + 2 + 2 + message.length());
		
		bb = ByteBuffer.allocate(1400) ;
		bb.putShort(ID);
		bb.put(surnom);
		bb.putShort(seq);
		bb.putShort(taille);
		bb.put(message.getBytes());		
		bb.limit(taille);
	}
	
	public MyMessage(short id, String surnom_var, short seq_var, String content){
		ID = id;
		surnom = new byte[6];
		surnom = surnom_var.getBytes();
		seq = seq_var;
		message = content;		
		taille = (short)(2 + 6 + 2 + 2 + message.length());
		
		bb = ByteBuffer.allocate(1400) ;
		bb.putShort(ID);
		bb.put(surnom);
		bb.putShort(seq);
		bb.putShort(taille);
		bb.put(message.getBytes());		
		bb.limit(taille);
	}
	
	public ByteBuffer getBuf(){				
		return bb;
	}
	
	public MyMessage(ByteBuffer buf){
		bb = buf;
		ID = bb.getShort(0); // 2 first bytes
//		bb.get(surnom, 2, 6);	// next 6 bytes	
		surnom = (new String (buf.array(), 2, 6)).getBytes();
		seq = bb.getShort(8); // next 2 bytes
		taille = bb.getShort(10); // next 2 bytes
//		System.out.println("buf.limit()=" + buf.limit());
		message = new String (buf.array(), 12, buf.position() - 12);
	}
	
	public short getID(){
		return ID;
	}
	
	public short getSeq(){
		return seq;
	}
	
	public short getTaille(){
		return taille;
	}
	
	public String getMessage(){
		return message;
	}
	
	public String getSurNom(){
		return new String (surnom, 0, 6);
	}
	
	public void printAllField(){
		System.out.println("Receive: " + this.getID()
						+ " " + this.getSurNom()
						+ " " + this.getSeq()
						+ " " + this.getTaille()
						+ " " + this.getMessage());
		/*System.out.println("ID = " + this.getID());
		System.out.println("name = " + this.getSurNom());
		System.out.println("seq = " + this.getSeq());
		System.out.println("taille = " + this.getTaille());
		System.out.println("message = " + this.getMessage());*/
	}
}
